#!/usr/bin/env node

import https from 'https'
import fs from 'fs'
import path from 'path'
import os from 'os'
import { fileURLToPath } from 'url'

// 获取当前文件的目录路径（ES模块中__dirname不可用）
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 读取 package.json 获取 Electron 版本
const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8'))
const electronVersion = packageJson.devDependencies.electron.replace('^', '')

console.log(`正在下载 Electron ${electronVersion}...`)

// 设置缓存目录
const cacheDir = path.join(os.homedir(), '.electron-cache')
if (!fs.existsSync(cacheDir)) {
  fs.mkdirSync(cacheDir, { recursive: true })
}

// 可用的镜像源（按优先级排序）
const mirrors = [
  'https://npmmirror.com/mirrors/electron/',
  'https://mirrors.huaweicloud.com/electron/',
  'https://mirrors.ustc.edu.cn/electron/',
  'https://registry.npmmirror.com/-/binary/electron/',
  'https://mirrors.tuna.tsinghua.edu.cn/electron/'
]

// 构建下载 URL
const platform = process.platform === 'win32' ? 'win32' : process.platform
const arch = process.arch === 'x64' ? 'x64' : process.arch
const filename = `electron-v${electronVersion}-${platform}-${arch}.zip`

async function downloadWithMirror(mirror, attempt = 0) {
  if (attempt >= mirrors.length) {
    throw new Error('所有镜像源都尝试失败')
  }

  const currentMirror = mirrors[attempt]
  const url = `${currentMirror}${electronVersion}/${filename}`
  const outputPath = path.join(cacheDir, filename)

  console.log(`尝试镜像 ${attempt + 1}/${mirrors.length}: ${currentMirror}`)
  console.log(`下载地址: ${url}`)

  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(outputPath)
    
    https.get(url, (response) => {
      if (response.statusCode === 200) {
        const totalSize = parseInt(response.headers['content-length'], 10)
        let downloadedSize = 0

        response.on('data', (chunk) => {
          downloadedSize += chunk.length
          const progress = ((downloadedSize / totalSize) * 100).toFixed(1)
          process.stdout.write(`\r下载进度: ${progress}% (${(downloadedSize / 1024 / 1024).toFixed(1)}MB / ${(totalSize / 1024 / 1024).toFixed(1)}MB)`)
        })

        response.pipe(file)
        
        file.on('finish', () => {
          file.close()
          console.log(`\n✅ 下载完成: ${outputPath}`)
          resolve(outputPath)
        })
      } else if (response.statusCode === 302 || response.statusCode === 301) {
        // 处理重定向
        const redirectUrl = response.headers.location
        console.log(`重定向到: ${redirectUrl}`)
        https.get(redirectUrl, (redirectResponse) => {
          redirectResponse.pipe(file)
          file.on('finish', () => {
            file.close()
            console.log(`\n✅ 下载完成: ${outputPath}`)
            resolve(outputPath)
          })
        }).on('error', (err) => {
          fs.unlink(outputPath, () => {})
          reject(err)
        })
      } else {
        fs.unlink(outputPath, () => {})
        reject(new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`))
      }
    }).on('error', (err) => {
      fs.unlink(outputPath, () => {})
      reject(err)
    })
  }).catch(async (error) => {
    console.log(`\n❌ 镜像 ${attempt + 1} 失败: ${error.message}`)
    return downloadWithMirror(mirror, attempt + 1)
  })
}

// 开始下载
downloadWithMirror()
  .then((filePath) => {
    console.log('\n🎉 Electron 下载成功！')
    console.log(`文件位置: ${filePath}`)
    console.log('\n现在可以运行 pnpm run electron:build 进行打包了')
  })
  .catch((error) => {
    console.error('\n❌ 下载失败:', error.message)
    console.log('\n请检查网络连接或尝试手动下载')
    process.exit(1)
  })